﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UnitDetailPanel : MonoBehaviour
{
    public BoardDisplay BoardDisplay;
    public GameObject Root;
    public GameObject TextPrefab;
    public RectTransform BuffInfoPanel;
    public Text NameText;

    List<GameObject> CurrentTexts = new List<GameObject>();
    bool isShowing;

    void Start()
    {
        MessageManager<GameObject>.Instance.AddListener(ClientEvent.StartLongPressObject, OnStartLongPress);
        Root = transform.GetChild(0).gameObject;
        Root.SetActive(false);
    }

    void OnDestroy()
    {
        MessageManager<GameObject>.Instance.RemoveListener(ClientEvent.StartLongPressObject, OnStartLongPress);
    }
    private void Update()
    {
        if (isShowing)
        {
            var curMouse = MyInputSystem.Instance.curMouse;
            if (!curMouse.pressing || curMouse.castObject != MyInputSystem.Instance.pressStartMouse.castObject)
            {
                OnEndPress();
            }
        }
    }

    public void OnStartLongPress(GameObject go)
    {
        CellDisplay cellDisplay = go.GetComponent<CellDisplay>();
        if (cellDisplay != null)
        {
            UnitBase unit = cellDisplay.m_Cell.Unit;
            if (unit != null && (unit.team == BoardDisplay.m_ViewPoint || unit.visible_to_opponent))
            {
                SetUnit(unit, BoardDisplay.m_ViewPoint);
            }
        }
        isShowing = true;
    }

    public void SetUnit(UnitBase unit, Team viewer)
    {
        Root.SetActive(true);
        // 优化点，复用创建好的object
        foreach (GameObject go in CurrentTexts)
        {
            Destroy(go);
        }
        CurrentTexts.Clear();

        NameText.text = unit.ToString();
        NameText.color = unit.team == viewer ? Color.white : Color.red;

        foreach (var buffs in unit.buffs.Values)
        {
            foreach (var buff in buffs)
            {
                GameObject textGo = GameObject.Instantiate(TextPrefab, BuffInfoPanel);
                textGo.GetComponent<Text>().text = buff.ToString();
                CurrentTexts.Add(textGo);
            }
        }
    }
    public void OnEndPress()
    {
        Root.SetActive(false);
        isShowing = false;
    }
}
